package com.wnxy.log;
import java.util.Arrays;
import java.util.Date;

import com.wnxy.entity.SysLog;
import com.wnxy.service.SysLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 日志的切面类
 */
@Component
@Aspect
public class LogAspect {

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private SysLogService sysLogService;

    // 环绕通知： 拦截指定的注解
    @Around("@annotation(systemLog)")
    public Object insertLog(ProceedingJoinPoint pjp, SystemLog systemLog) throws Throwable {
        long start = System.currentTimeMillis();
        // 获取当前执行的方法参数
        Object[] args = pjp.getArgs();
        // 执行方法, 获取方法返回值
        Object retV = pjp.proceed(args);

        // 计算方法执行时长
        long time = System.currentTimeMillis() - start;

        // 封装日志对象, 保存日志
        SysLog sysLog = new SysLog();
        sysLog.setUname("小猿");
        sysLog.setOperation(systemLog.value());
        sysLog.setTime(time);
        sysLog.setCreateTime(new Date());
        sysLog.setIp(request.getRemoteAddr());
        // 方法名称
        sysLog.setMethod(pjp.getSignature().getName());
        // 方法参数
        sysLog.setParams(Arrays.toString(args));
        // 保存日志
        sysLogService.save(sysLog);
        return retV;
    }
}
